package com.dave.admin.component.dict;

import cn.hutool.core.util.StrUtil;
import com.dave.admin.component.SpringContextHolder;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Dave
 * @version 1.0
 */

public class DictBeanSerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
                                                     List<BeanPropertyWriter> beanProperties) {
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = beanProperties.get(i);
            Dict dict = writer.getAnnotation(Dict.class);
            if (Objects.nonNull(dict) && StrUtil.isNotBlank(dict.type())) {
                writer.assignSerializer(new DictJsonSerializer(dict.target(), getDictBind(dict.type())));
            }
        }
        return beanProperties;
    }


    public DictBind getDictBind(String type) {
        Map<String, DictBind> dictBindMap = SpringContextHolder.getApplicationContext().getBeansOfType(DictBind.class);
        return dictBindMap.get(type);
    }
}